﻿using EasyOAuth.Core.Web;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Text;

namespace EasyOAuth
{
    /// <summary>
    /// 全局异常过滤
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        /// <summary>
        /// 全局异常过滤
        /// </summary>
        public GlobalExceptionFilter() { }
        /// <summary>
        /// 错误捕获
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {

            var ex = context.Exception;
            var request = context.HttpContext.Request;
            var url = request.Host + request.Path;
            if (!request.QueryString.HasValue)
            {
                url += request.QueryString;
            }
            var method = request.Method;
            var userHostAddress = context.HttpContext.Connection.RemoteIpAddress?.ToString();
            var logContent = new StringBuilder();
            logContent.Append($"接口地址：{url} ");
            logContent.Append($"请求IP：{userHostAddress}");
            logContent.Append($"请求方法：{method} ");
            logContent.Append($"错误内容：[{ex.Message}] [{ex.Source}] {ex} ");
            //UseLog.Debug(logContent.ToString(), "全局错误");

            var apiResult = new ApiResult()
            {
                Msg = ex.Message,
                Code = -1
            };

            //如果直接手动实现统一格式 这里可以注释掉
            if (ex is ApiResException res)
            {
                apiResult.Code = res.Code;
                apiResult.Data = res.DataResult;

            }
            context.Result = new JsonResult(apiResult);
            context.ExceptionHandled = true;    //设置异常已经处理
        }
    }
}